package inesv.utils;

import com.alibaba.fastjson.JSON;
import inesv.dto.User;
import org.apache.commons.codec.digest.HmacUtils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.util.CollectionUtils;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @BelongsPackage: sign
 * @Author: linqh03
 * @CreateTime: 2021-02-03 14:01
 * @Description: 接口签名工具类
 */
public class SignUtil {

    public static String sign(String appSecret,String body, Map<String, String[]> params, String[] paths) {
        StringBuilder sb = new StringBuilder();
        if (StringUtils.isNotBlank(body)) {
            sb.append(body).append('#');
        }

        if (!CollectionUtils.isEmpty(params)) {
            params.entrySet()
                    .stream()
                    .sorted(Map.Entry.comparingByKey())
                    .forEach(paramEntry -> {
                        String paramValue = String.join(",", Arrays.stream(paramEntry.getValue()).sorted().toArray(String[]::new));
                        sb.append(paramEntry.getKey()).append("=").append(paramValue).append('#');
                    });
        }

        if (ArrayUtils.isNotEmpty(paths)) {
            String pathValues = String.join(",", Arrays.stream(paths).sorted().toArray(String[]::new));
            sb.append(pathValues);
        }
        String signStr = sb.toString();
        if (signStr.endsWith("#")){
            signStr = signStr.substring(0,signStr.length()-1);
        }
        System.out.println("#签名前：" +signStr );
        String createSign = HmacUtils.hmacSha256Hex(appSecret, signStr);
        System.out.println("#签名后：" + createSign);
        return createSign;
    }


    public static void main(String[] args) {

        User user = new User();
        user.setId(1L);
        user.setUsername("ADMIN");
        user.setPhone("15629876888");

        Map<String, String[]> params = new HashMap<>();
        params.put("var3", new String[]{"3"});
        params.put("var4", new String[]{"4"});

        String[] paths = new String[]{"1", "2"};

        System.out.println(sign("123", JSON.toJSONString(user), null, null));
    }

}
